package com.zzwc.vote.www.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zzwc.vote.exception.ZhiZhiException;
import com.zzwc.vote.www.entity.VoteUser;
import com.zzwc.vote.www.mapper.VoteUserMapper;
import com.zzwc.vote.www.service.IVoteUserService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author weirdor
 * @since 2018-06-06
 */
@Service
public class VoteUserServiceImpl extends ServiceImpl<VoteUserMapper, VoteUser> implements IVoteUserService {

    @Autowired
    private WxMpService wxService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(String code) {

        try {
            String openId = wxService.oauth2getAccessToken(code).getOpenId();

            EntityWrapper<VoteUser> wrapper = new EntityWrapper<>();

            wrapper.eq("open_id", openId);

            VoteUser voteUser = super.selectOne(wrapper);

            //判断是否重复
            if (voteUser == null) {
                //判断是否关注微信公众号
                boolean subscribe = wxService.getUserService().userInfo(openId).getSubscribe();
                if (subscribe) {
                    VoteUser user = new VoteUser();
                    //创建时间
                    user.setCreateTime(new Date());
                    //获取用户的性别
                    int sex = wxService.getUserService().userInfo(user.getOpenId()).getSex();
                    user.setSex(sex);
                    String headImgUrl = wxService.getUserService().userInfo(user.getOpenId()).getHeadImgUrl();
                    user.setHeadImg(headImgUrl);
                    String nickName = wxService.getUserService().userInfo(user.getOpenId()).getNickname();
                    user.setNickName(nickName);
                    super.insert(user);
                }
            }
        } catch (WxErrorException e) {
            int errcode = e.getError().getErrorCode();
            if (errcode == 40014 || errcode == 42001 || errcode == 40001) {
                try {
                    wxService.oauth2refreshAccessToken(code);
                } catch (WxErrorException e1) {
                    throw new ZhiZhiException(e.getError().getJson());
                }
            }
            throw new ZhiZhiException(e.getError().getJson());
        }
    }
}
